package com.zhou.base.components.bs.common.validator;

import com.google.common.collect.Sets;

import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Payload;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.Collection;
import java.util.HashSet;

import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import static java.lang.annotation.ElementType.CONSTRUCTOR;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.ElementType.TYPE_USE;

/**
 * @author xianfeng
 * @date 2023/8/9 11:47
 */
@Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = ListNotRepeat.Validator.class)
public @interface ListNotRepeat {

    String message() default "{custom.list.not.repeat.error}";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

    class Validator implements ConstraintValidator<ListNotRepeat, Object> {

        @Override
        public void initialize(ListNotRepeat enumValue) {
        }

        @Override
        public boolean isValid(Object value, ConstraintValidatorContext constraintValidatorContext) {
            if (value != null && value instanceof Collection) {
                Collection coll = (Collection) value;
                HashSet hashSet = Sets.newHashSet(coll);
                if (coll.size() != hashSet.size()) {
                    return false;
                }
            }
            return true;
        }

    }
}
